package com.zpark.user_system.dao.impl;

import com.zpark.user_system.bean.User;
import com.zpark.user_system.dao.IUserDao;
import com.zpark.user_system.utils.JDBCUtils;

import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户持久层接口实现类
 */
public class UserDaoImpl implements IUserDao {

    /**
     * 用户登录接口
     * @param username 用户名字
     * @return
     */
    @Override
    public User loginSelect(String username) {
        // 根据用户名向数据库查询数据
        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet res = null;

        User user = null;

        try {
            // 获取数据库连接对象
            conn = JDBCUtils.getConnection();
            // 编写sql语句
            String sql = "select id, username, password, sex, language, city from user where username = ?";
            // 获取sql预编译对象
            stat = conn.prepareStatement(sql);
            // 替换占位符
            stat.setString(1, username);
            // 执行sql
            res = stat.executeQuery();

            // 获取遍历结果集
            while (res.next()) {
                user = new User();
                user.setUsername(res.getString("username"));
                user.setId(res.getInt("id"));
                user.setPassword(res.getString("password"));
                user.setLanguage(res.getString("language"));
                user.setSex(res.getString("sex"));
                user.setCity(res.getString("city"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            JDBCUtils.close(conn, stat, res);
        }
        return user;
    }
}
